package com.guangli.ocr.ui

import android.Manifest
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.Bitmap
import android.os.Bundle
import android.view.Surface
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.baidu.idcardquality.IDcardQualityProcess
import com.baidu.ocr.sdk.OCR
import com.baidu.ocr.ui.camera.*
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.guangli.base.base.activity.RobotBaseActivity
import com.guangli.base.util.FileUtil
import com.guangli.ocr.R
import com.guangli.ocr.api.RecognizeService
import com.guangli.ocr.databinding.ActivityVehicleLicenseBinding
import com.guangli.ocr.model.DrivingLicenseModel
import com.guangli.ocr.viewmodel.VehicleLicenseViewModel
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class VehicleLicenseActivity :
    RobotBaseActivity<ActivityVehicleLicenseBinding, VehicleLicenseViewModel>() {

    override fun initContentView(savedInstanceState: Bundle?): Int =
        R.layout.activity_vehicle_license

    override fun initVariableId(): Int = 1
    var isNativeEnable = false
    private var outputFile: File? = null
    private var contentType: String = CameraActivity.CONTENT_TYPE_GENERAL
    private val permissionCallback = PermissionCallback {
        ActivityCompat.requestPermissions(
            this, arrayOf(Manifest.permission.CAMERA),
            CameraActivity.PERMISSIONS_REQUEST_CAMERA
        )
        false
    }

    override fun initComponents() {
        binding.cameraView.cameraControl.setPermissionCallback(permissionCallback)
        initParams()
//        init()
//        viewModel.isAndTheLiveEvent.observe(this, Observer {
//            contentType = if (it == "0") {
//                CameraActivity.CONTENT_TYPE_GENERAL
//            } else {
//                CameraActivity.CONTENT_TYPE_GENERAL
//            }
//            setMaskType()
////            binding.cameraView.getCameraControl().resume()
//            binding.cameraView.start()
//        })
    }

//    private fun init() {
//        //  初始化本地质量控制模型,释放代码在onDestory中
//        //  调用身份证扫描必须加上 intent.putExtra(CameraActivity.KEY_NATIVE_MANUAL, true); 关闭自动初始化和释放本地模型
//
//        //  初始化本地质量控制模型,释放代码在onDestory中
//        //  调用身份证扫描必须加上 intent.putExtra(CameraActivity.KEY_NATIVE_MANUAL, true); 关闭自动初始化和释放本地模型
//        CameraNativeHelper.init(
//            this, OCR.getInstance(this).license
//        ) { errorCode, e ->
//            val msg: String
//            msg = when (errorCode) {
//                CameraView.NATIVE_SOLOAD_FAIL -> "加载so失败，请确保apk中存在ui部分的so"
//                CameraView.NATIVE_AUTH_FAIL -> "授权本地质量控制token获取失败"
//                CameraView.NATIVE_INIT_FAIL -> "本地质量控制"
//                else -> errorCode.toString()
//            }
//            LogUtils.e("本地质量控制初始化错误，错误原因： $msg")
//        }
//    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            CameraActivity.PERMISSIONS_REQUEST_CAMERA -> {
                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    LogUtils.e("binding.cameraView.cameraControl.refreshPermission()")
                    binding.cameraView.cameraControl.refreshPermission()
                } else {
                    Toast.makeText(
                        applicationContext,
                        R.string.camera_permission_required,
                        Toast.LENGTH_LONG
                    )
                        .show()
                }
            }
            CameraActivity.PERMISSIONS_EXTERNAL_STORAGE -> {
            }
            else -> {
            }
        }
    }

    private fun initParams() {
        val outputPath = FileUtil.getSaveFile(getApplication()).getAbsolutePath()
        val token = intent.getStringExtra(CameraActivity.KEY_NATIVE_TOKEN)
        if (token == null) {
            isNativeEnable = false
        }
        if (outputPath != null) {
            outputFile = File(outputPath)
        }
        LogUtils.e(outputFile?.exists())

        setMaskType()
        setOrientation(resources.configuration)
//        cropMaskView.setMaskType(maskType)
    }

    private fun setMaskType() {
        val maskType: Int
        when (contentType) {
            CameraActivity.CONTENT_TYPE_ID_CARD_FRONT -> {
                maskType = MaskView.MASK_TYPE_ID_CARD_FRONT
            }
            CameraActivity.CONTENT_TYPE_ID_CARD_BACK -> {
                maskType = MaskView.MASK_TYPE_ID_CARD_BACK
            }
            CameraActivity.CONTENT_TYPE_BANK_CARD -> {
                maskType = MaskView.MASK_TYPE_BANK_CARD
            }
            CameraActivity.CONTENT_TYPE_PASSPORT -> {
                maskType = MaskView.MASK_TYPE_PASSPORT
            }
            CameraActivity.CONTENT_TYPE_GENERAL -> {
                maskType = MaskView.MASK_TYPE_NONE
            }
            else -> {
                maskType = MaskView.MASK_TYPE_NONE
            }
        }
        binding.cameraView.setEnableScan(true)
        binding.cameraView.setMaskType(maskType, this)
        binding.cameraView.setAutoPictureCallback(autoTakePictureCallback)
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        setOrientation(newConfig)
    }

    private fun setOrientation(newConfig: Configuration) {
        val rotation = windowManager.defaultDisplay.rotation
        val orientation: Int
        var cameraViewOrientation = CameraView.ORIENTATION_PORTRAIT
        when (newConfig.orientation) {
            Configuration.ORIENTATION_PORTRAIT -> {
                cameraViewOrientation = CameraView.ORIENTATION_PORTRAIT
                orientation = OCRCameraLayout.ORIENTATION_PORTRAIT
            }
            Configuration.ORIENTATION_LANDSCAPE -> {
                orientation = OCRCameraLayout.ORIENTATION_HORIZONTAL
                cameraViewOrientation =
                    if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) {
                        CameraView.ORIENTATION_HORIZONTAL
                    } else {
                        CameraView.ORIENTATION_INVERT
                    }
            }
            else -> {
                orientation = OCRCameraLayout.ORIENTATION_PORTRAIT
                binding.cameraView.setOrientation(CameraView.ORIENTATION_PORTRAIT)
            }
        }
//        takePictureContainer.setOrientation(orientation)
        binding.cameraView.setOrientation(cameraViewOrientation)
//        cropContainer.setOrientation(orientation)
//        confirmResultContainer.setOrientation(orientation)
    }

    private val autoTakePictureCallback: CameraView.OnTakePictureCallback =
        CameraView.OnTakePictureCallback { bitmap ->
            CameraThreadPool.execute {
                try {
                    val fileOutputStream: FileOutputStream =
                        FileOutputStream(outputFile)
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)
                    bitmap.recycle()
                    fileOutputStream.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
                LogUtils.e(contentType)
                RecognizeService.recognizeVehicleLicense(
                    this, FileUtil.getSaveFile(
                        applicationContext
                    ).absolutePath, object : RecognizeService.ServiceListener {
                        override fun onResult(it: String?) {
                            LogUtils.e(it)
                            val bean = GsonUtils.fromJson(it, DrivingLicenseModel::class.java)
                            if ((bean.words_result_num ?: 0) == 11) {
                                viewModel.isAndThe.set(true)
                                viewModel.cardNum.set(
                                    bean.words_result?.get("号牌号码")?.get("words")
                                )
                                viewModel.carType.set(bean.words_result?.get("车辆类型")?.get("words"))

                                viewModel.name.set(
                                    bean.words_result?.get("所有人")?.get("words")
                                )

                                viewModel.address.set(
                                    bean.words_result?.get("住址")?.get("words")
                                )

                                viewModel.usingNature.set(
                                    bean.words_result?.get("使用性质")?.get("words")
                                )

                                viewModel.brandModel.set(
                                    bean.words_result?.get("品牌型号")?.get("words")
                                )

                                viewModel.vehicleIdentificationCode.set(
                                    bean.words_result?.get("车辆识别代号")?.get("words")
                                )

                                viewModel.engineNum.set(
                                    bean.words_result?.get("发动机号码")?.get("words")
                                )

                                viewModel.registrationDate.set(
                                    bean.words_result?.get("注册日期")?.get("words")
                                )

                                viewModel.releaseDate.set(
                                    bean.words_result?.get("发证日期")?.get("words")
                                )

                                viewModel.licenseIssuingUnit.set(
                                    bean.words_result?.get("发证单位")?.get("words")
                                )
                            } else {
                                viewModel.isAndThe.set(false)
                                viewModel.deputyCardNum.set(
                                    bean.words_result?.get("号牌号码")?.get("words")
                                )
                                viewModel.fileNum.set(
                                    bean.words_result?.get("档案编号")?.get("words")
                                )
                                viewModel.authorizedCapacity.set(
                                    bean.words_result?.get("核定载人数")?.get("words")
                                )
                                viewModel.totalQuality.set(
                                    bean.words_result?.get("总质量")?.get("words")
                                )
                                viewModel.curbWeight.set(
                                    bean.words_result?.get("整备质量")?.get("words")
                                )
                                viewModel.approvedLoadMass.set(
                                    bean.words_result?.get("核定载质量")?.get("words")
                                )
                                viewModel.outsideProfileSize.set(
                                    bean.words_result?.get("外廓尺寸")?.get("words")
                                )
                                viewModel.quasiTotalMass.set(
                                    bean.words_result?.get("准牵引总质量")?.get("words")
                                )
                                viewModel.remark.set(
                                    bean.words_result?.get("备注")?.get("words")
                                )
                                viewModel.inspectionRecord.set(
                                    bean.words_result?.get("检验记录")?.get("words")
                                )

                                viewModel.fuelRecord.set(
                                    bean.words_result?.get("燃油类型")?.get("words")
                                )
                                viewModel.theCoreCode.set(
                                    bean.words_result?.get("证芯编号")?.get("words")
                                )
                            }
                            binding.cameraView.cameraControl.resume()
                            binding.cameraView.setAbortingScan(false);
                        }

                        override fun onError(error: String?) {
                            binding.cameraView.cameraControl.resume()
                            binding.cameraView.setAbortingScan(false);
                        }
                    }
                )
            }
        }

    /**
     * 做一些收尾工作
     *
     */
    private fun doClear() {
        CameraThreadPool.cancelAutoFocusTimer()
        if (isNativeEnable) {
            IDcardQualityProcess.getInstance().releaseModel()
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        doClear()
    }
}